package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Transactional
@Controller
@RequestMapping("/cargo/contractProduct")
public class CargoProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list",name ="跳转到新增货物页面")
    public String list(String contractId,@RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10")int pageSize){

        //构建查询条件   通过合同id 查询所有货物
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<Contract> pageInfo =  contractProductService.findAll(example,page,pageSize);
        request.setAttribute("page",pageInfo);

        /*查询所有的货物生产厂家*/
        /*构建查询条件 ctype="货物"*/
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        /*页面需要的隐藏数据 contractId*/
        request.setAttribute("contractId",contractId);

        return "/cargo/product/product-list";
    }



    @RequestMapping(value = "/toAdd",name = "跳转到新增货物页面")
    public String toAdd(){

        return "/cargo/Product/Product-add";
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;
    @RequestMapping(value = "/edit",name = "跳转到新增货物方法")
     public String edit(ContractProduct contractProduct,MultipartFile productPhoto)  {
//         完成货物图片上传
        String imgUrl="";
        try {
            if (productPhoto!=null) {
                 imgUrl = fileUploadUtil.upload(productPhoto);//返回的是路径
            }
        } catch (Exception e) {
            e.printStackTrace();
            contractProduct.setProductImage(null);
        }
        contractProduct.setProductImage(imgUrl);



        //*货物id 为空即新增 不为空即 保存*//*
         if (StringUtils.isEmpty(contractProduct.getId())) {
             //设置id 公司id  公司名
             contractProduct.setId(UUID.randomUUID().toString());
             contractProduct.setCompanyName(getCompanyName());
             contractProduct.setCompanyId(getCompanyId());
             contractProduct.setCreateTime(new Date());
             contractProductService.save(contractProduct);

         }else{
             /*编辑*/
             contractProductService.update(contractProduct);
         }


         return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
     }


   @RequestMapping(value = "/toUpdate",name = "跳转到编辑货物页面")
   public String toUpdate(String id){//货物id
       //*数据回显 根据合同id  查找对应合同*//*
       ContractProduct contractProduct = contractProductService.findById(id);
       request.setAttribute("contractProduct",contractProduct);

       /*查询所有的货物生产厂家*/
       /*构建查询条件 ctype="货物"*/
       FactoryExample factoryExample = new FactoryExample();
       factoryExample.createCriteria().andCtypeEqualTo("货物");
       List<Factory> factoryList = factoryService.findAll(factoryExample);
       request.setAttribute("factoryList",factoryList);

       return "/cargo/product/product-update";
   }



    @RequestMapping(value = "/delete",name = "删除货物")
    public String delete(String id,String contractId ){

        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    @RequestMapping(value = "/toImport",name = "进入到上传货物表页面")
    public String toImport(String contractId ){

        request.setAttribute("contractId",contractId);

        return "/cargo/product/product-import";
    }


    @RequestMapping(value = "/import",name = "进入到上传货物表页面")
    public String importXlsx(String contractId,MultipartFile file) throws Exception {

        Workbook workbook = new XSSFWorkbook(file.getInputStream());//创建工作簿（有内容的）

        Sheet sheet = workbook.getSheetAt(0);//获取工作簿中的第一个工作表

        int lastRowNum = sheet.getLastRowNum();//获取最后一行的索引值

        ContractProduct product = null;
        Row row= null;
        List<ContractProduct> productList = new ArrayList<>();
        for (int i =1; i <=lastRowNum ; i++) {

            product = new ContractProduct();

             row = sheet.getRow(i);//获取行

            //生产厂家	货号	数量	包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求

            String factoryName = row.getCell(1).getStringCellValue(); //生产厂家
            product.setFactoryName(factoryName);

            String productNo = row.getCell(2).getStringCellValue(); //货号
            product.setProductNo(productNo);

            Integer cnumber = ((Double)row.getCell(3).getNumericCellValue()).intValue(); //数量
            product.setCnumber(cnumber);

            String packingUnit = row.getCell(4).getStringCellValue(); //包装单位(PCS/SETS)
            product.setPackingUnit(packingUnit);

            String loadingRate = ((Double)row.getCell(5).getNumericCellValue()).toString(); //装率 string
            product.setLoadingRate(loadingRate);

            Integer boxNum = ((Double)row.getCell(6).getNumericCellValue()).intValue(); //箱数 Integer
            product.setBoxNum(boxNum);

            Double price = row.getCell(7).getNumericCellValue(); //单价 double
            product.setPrice(price);

            //还需要添加默认的数据 id、所属的合同ID 、企业id 、企业名称
            product.setId(UUID.randomUUID().toString());
            product.setCompanyId(getCompanyId());
            product.setCompanyName(getCompanyName());
            product.setContractId(contractId);

            productList.add(product);

        }
        contractProductService.saveList(productList);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }
}
